package com.qf.springboot230203.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.kaptcha.Kaptcha;
import com.qf.springboot230203.entity.OnePiece;
import com.qf.springboot230203.ex.OnepieceException;
import com.qf.springboot230203.service.OnePieceService;
import com.qf.springboot230203.utils.Constants;
import com.qf.springboot230203.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.Date;

@RestController
@RequestMapping("/onepiece")
@Slf4j
public class OnePieceController {

    @Autowired
    private Kaptcha kaptcha;

    @Autowired
    OnePieceService onePieceService;

    @Value("${qfsy.lyt.path}")
    private String filepath;

    @Value("${qfsy.fileupload.path}")
    String filepa;

    @GetMapping("/render")
    public void render() {
        kaptcha.render();
    }

    /**
     * 登入接口
     *
     * @param username
     * @param password
     * @param captchar
     * @param switch1
     * @param session
     * @param response
     * @return
     */
    @PostMapping("/login")
    public ResultVo login(String username, String password, String captchar, String switch1, HttpSession session, HttpServletResponse response) {
        //1.打印日志
        log.debug("接口入参：username={},password={},captchar={}", username, password, captchar);

        //2.校验验证码
        kaptcha.validate(captchar);

        //3.查询数据库验证用户名和密码是否匹配
        //service层的方法
        //（1）要把处理业务逻辑所需要的参数都传给该方法
        //返回值需满足web接口返回 json数据的需求
        OnePiece onePiece = onePieceService.login(username, password);

        //4.判断
        if (onePiece == null) {
            /*ResultVo resultVo = new ResultVo(-1, "用户名密码错误");*/
            return ResultVo.error("用户名密码错误");
        } else {
            //判断用户是否免登录
            if (switch1 != null && switch1.equals("on")) {
                //设置cookie
                String onePieceCookie = username + "/" + password;
                Cookie cookie = new Cookie(Constants.ONEPIECE_COOKIE_KEY, onePieceCookie);
                //设置cookie存活时间
                cookie.setMaxAge(60 * 60 * 24 * 14);
                cookie.setPath("/");
                //将cookie加入浏览器中
                response.addCookie(cookie);
            }
            ResultVo resultVo = ResultVo.ok();
            session.setAttribute(Constants.ONEPIECE_SESSION_KEY, onePiece);
            resultVo.put("data", onePiece);
            return resultVo;
        }

    }

    @PostMapping("/regist")
    public ResultVo regist(OnePpieceVo onePpieceVo, HttpSession session) throws IOException {

        kaptcha.validate(onePpieceVo.getCaptchar());

        onePieceService.insertOnePiece(onePpieceVo);

        return ResultVo.ok();
    }

    /**
     * 判断用户名是否已被注册过
     * @param username
     * @return
     */
    @GetMapping("/uname")
    public ResultVo uName(String username){

        OnePiece onePiece = onePieceService.uname(username);
        if (onePiece != null){
            return ResultVo.error("该用户名重复");
        }
        return ResultVo.ok() ;
    }

    /**
     * 判断用户俩次密码是否一致
     * @param password
     * @param password1
     * @return
     */
    @PostMapping("/pass")
    public ResultVo pass(String password,String password1){
        if (password.equals(password1)){
            return ResultVo.ok();
        }
        return ResultVo.error("俩次密码不一致");
    }

    @GetMapping("/getall")
    public TableVO<OnePiece> getAll(PagingVo pagingVo){

        TableVO<OnePiece> vo = onePieceService.getAllLimtit(pagingVo);

        return vo;
    }

    /**
     * 修改
     * @param o
     * @return
     * @throws OnepieceException
     */
    @PostMapping("/add")
    public ResultVo add(OnePiece2VO o) throws OnepieceException {
        onePieceService.addInsert(o);
        return ResultVo.ok();
    }

    @RequestMapping("/del")
    public ResultVo del(Integer[] ids){

        log.debug("入参为：ids={}",ids);
        onePieceService.delId(ids);
        return ResultVo.ok();
    }

    @RequestMapping("/update")
    public ResultVo updata(OnePiece onePiece) throws OnepieceException {
        log.debug("入参为：onePiece2VO={}",onePiece);
        onePieceService.updata(onePiece);
        return ResultVo.ok();
    }


    @GetMapping("/export")
    public ResultVo export(){
        String fileName = onePieceService.getAllOnePiece(filepath);
        ResultVo vo = new ResultVo();
        vo.put("data",fileName);
        return vo;
    }

    @GetMapping("/download")
    public ResultVo download(String filename,HttpServletResponse response) throws IOException {
        //根据文件名拿到文件位置
        String file = filepath + filename;
        String fileNameUUid = UUID.randomUUID().toString();

        //设置响应头,告知浏览器,要以附件的形式保存内容
        response.setHeader("content-disposition","attachment;filename="+fileNameUUid);
        IoUtil.copy(new FileInputStream(file),response.getOutputStream());

        return ResultVo.ok();
    }

    /**
     * 用户头像和用户名
     * @return
     */
    @GetMapping("/img")
    public ResultVo headPortrait(HttpServletRequest request, HttpServletResponse response){

        //打印日志
        log.debug("登入成功");

        //获取session对象和数据
        HttpSession session = request.getSession();
        OnePiece onePiece = (OnePiece) session.getAttribute(Constants.ONEPIECE_SESSION_KEY);

        //调用service层方法查数据库
        OnePiece piece = onePieceService.uname(onePiece.getName());

        log.debug("用户信息：piece={}",piece);

        //响应给客户端
        ResultVo vo = new ResultVo();
        vo.put("name",piece.getName());
        vo.put("img",piece.getPhotopath());
        return vo;
    }

    @GetMapping("/pic")
    public void photo(String picname,HttpSession session,HttpServletResponse response) throws IOException {
        String filepath = filepa + picname;
        IoUtil.copy(new FileInputStream(filepath),response.getOutputStream());

    }

    /**
     * 批量上传接口
     * @return
     */
    @PostMapping("/upload")
    public ResultVo upload(MultipartFile file,HttpServletRequest request,HttpServletResponse response) throws IOException {

        //拿到原始文件名
        String originalFilename = file.getOriginalFilename();
        String file1 = filepath+originalFilename;

        BufferedReader br = new BufferedReader(new FileReader(file1));
        String str;
        while ((str = br.readLine()) != null){
            OnePiece onePiece = OnePiece.csvToBook(str);
            onePieceService.insertAll(onePiece);
        }

        br.close();

        return ResultVo.ok();
    }



}
